<template>
  <PageCard title="AI测姓名" titleEnglish="AI Name Analysis">
    <div class="name-analysis-container">
      <n-grid :cols="12" :x-gap="24" :y-gap="24">
        <n-grid-item :span="inputCardSpan">
          <n-card title="输入信息" embedded :bordered="false">
            <n-space vertical>
              <n-alert type="info" :bordered="false">
                请输入您的姓名和基本信息，AI将为您进行深度姓名分析。
              </n-alert>

              <n-form
                ref="formRef"
                :model="formData"
                :rules="rules"
                label-placement="left"
                label-width="auto"
                require-mark-placement="right-hanging"
              >
                <n-form-item label="姓名" path="name">
                  <n-input
                    v-model:value="formData.name"
                    placeholder="请输入您的姓名"
                    clearable
                    :maxlength="20"
                  />
                </n-form-item>

                <n-form-item label="性别" path="gender">
                  <n-radio-group v-model:value="formData.gender">
                    <n-space>
                      <n-radio value="男">男</n-radio>
                      <n-radio value="女">女</n-radio>
                      <n-radio value="不想说">不想说</n-radio>
                    </n-space>
                  </n-radio-group>
                </n-form-item>

                <n-form-item label="出生年份" path="birthYear">
                  <n-input-number
                    v-model:value="formData.birthYear"
                    placeholder="选填，如：1990"
                    :min="1900"
                    :max="currentYear"
                    :show-button="false"
                    clearable
                  />
                </n-form-item>
              </n-form>

              <n-button
                type="primary"
                block
                size="large"
                :loading="analyzing"
                @click="analyzeName"
              >
                <template #icon>
                  <n-icon>
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
                      <path fill="currentColor" d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/>
                    </svg>
                  </n-icon>
                </template>
                开始AI分析
              </n-button>

              <n-button
                v-if="analysisResult"
                type="default"
                block
                size="large"
                @click="resetForm"
              >
                重新分析
              </n-button>
            </n-space>
          </n-card>
        </n-grid-item>

        <n-grid-item :span="resultCardSpan">
          <n-card title="分析结果" embedded :bordered="false">
            <div v-if="!analysisResult && !isAnalyzing" class="empty-result">
              <n-empty description="输入姓名信息后点击分析按钮查看结果" />
            </div>

            <div v-else-if="isAnalyzing && !analysisResult" class="loading-state">
              <n-spin size="large" :show="true">
                <template #description>
                  <n-text :style="{ fontSize: isMobile ? '14px' : '16px' }">
                    正在分析中，请稍候...
                  </n-text>
                </template>
              </n-spin>
            </div>

            <div v-else class="analysis-result">
              <n-space vertical>
                <div class="streaming-result" :class="{ 'is-streaming': isAnalyzing }" v-if="analysisResult">
                  <MarkdownRenderer :content="analysisResult" />
                </div>

                <n-divider v-if="!isAnalyzing" />

                <n-space v-if="!isAnalyzing">
                  <n-button @click="saveResult" type="info">
                    <template #icon>
                      <n-icon>
                        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
                          <path fill="currentColor" d="M17 3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V7l-4-4zm-5 16c-1.66 0-3-1.34-3-3s1.34-3 3-3 3 1.34 3 3-1.34 3-3 3zm3-10H5V5h10v4z"/>
                        </svg>
                      </n-icon>
                    </template>
                    保存结果
                  </n-button>
                  <n-button @click="shareResult" type="success">
                    <template #icon>
                      <n-icon>
                        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
                          <path fill="currentColor" d="M18 16.08c-.76 0-1.44.3-1.96.77L8.91 12.7c.05-.23.09-.46.09-.7s-.04-.47-.09-.7l7.05-4.11c.54.5 1.25.81 2.04.81 1.66 0 3-1.34 3-3s-1.34-3-3-3-3 1.34-3 3c0 .24.04.47.09.7L8.04 9.81C7.5 9.31 6.79 9 6 9c-1.66 0-3 1.34-3 3s1.34 3 3 3c.79 0 1.5-.31 2.04-.81l7.12 4.16c-.05.21-.08.43-.08.65 0 1.61 1.31 2.92 2.92 2.92 1.61 0 2.92-1.31 2.92-2.92s-1.31-2.92-2.92-2.92z"/>
                        </svg>
                      </n-icon>
                    </template>
                    分享结果
                  </n-button>
                </n-space>
              </n-space>
            </div>
          </n-card>
        </n-grid-item>
      </n-grid>
    </div>
    
    <n-divider />
    
    <UsageGuide
      :title="usageGuideConfig.title"
      :steps="usageGuideConfig.steps"
      :tips="usageGuideConfig.tips"
      :example="usageGuideConfig.example"
    />
  </PageCard>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import {
  NGrid,
  NGridItem,
  NCard,
  NButton,
  NIcon,
  NText,
  NSpace,
  NAlert,
  NEmpty,
  NDivider,
  NSpin,
  NForm,
  NFormItem,
  NInput,
  NInputNumber,
  NRadioGroup,
  NRadio,
  useMessage,
  FormInst,
  FormRules
} from 'naive-ui'
import PageCard from '@/components/PageCard.vue'
import UsageGuide from '@/components/UsageGuide.vue'
import MarkdownRenderer from '@/components/MarkdownRenderer.vue'
import { NameAnalysisApi } from '@/api/entertainment/nameAnalysis'
import { SSEClient } from '@/utils/sse'
import { useBreakpoint } from '@/utils/responsive-helper'

const message = useMessage()

// 响应式布局
const { isMobile } = useBreakpoint()

// 根据屏幕大小计算 span
const inputCardSpan = computed(() => isMobile.value ? 12 : 6)
const resultCardSpan = computed(() => isMobile.value ? 12 : 6)

// 当前年份
const currentYear = new Date().getFullYear()

// 表单相关
const formRef = ref<FormInst | null>(null)
const formData = ref({
  name: '',
  gender: '男',
  birthYear: null as number | null
})

const rules: FormRules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 1, max: 20, message: '姓名长度应在1-20个字符之间', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  birthYear: [
    { type: 'number', min: 1900, max: currentYear, message: `出生年份应在1900-${currentYear}之间`, trigger: 'blur' }
  ]
}

// 分析相关
const analyzing = ref(false)
const analysisResult = ref<string>('')
const isAnalyzing = ref(false)

// UsageGuide configuration
const usageGuideConfig = {
  title: '使用说明',
  steps: [
    '输入您的姓名（必填）',
    '选择性别（必填）',
    '输入出生年份（选填，用于更精准的分析）',
    '点击"开始AI分析"按钮',
    '等待AI分析完成，查看详细的姓名解读结果'
  ],
  tips: [
    '姓名分析包含音韵学、字形结构、文化内涵等多个维度',
    '分析结果包括五行属性、人生发展建议等内容',
    '支持保存和分享分析结果',
    'AI分析仅供娱乐参考，不代表科学依据'
  ],
  example: '例如：输入"张三"、选择"男"、输入"1990"，即可获得完整的姓名分析报告'
}

// 分析姓名
const analyzeName = async () => {
  // 验证表单
  try {
    await formRef.value?.validate()
  } catch (error) {
    return
  }

  analyzing.value = true
  isAnalyzing.value = true
  analysisResult.value = ''

  try {
    const params = {
      name: formData.value.name,
      gender: formData.value.gender,
      ...(formData.value.birthYear && { birthYear: formData.value.birthYear })
    }

    const reader = await NameAnalysisApi.analyzeName(params)

    await SSEClient.processStream(reader, {
      targetRef: analysisResult,
      clearBeforeStart: true,
      onError: (err) => {
        message.error(err.message || '分析失败，请重试')
      },
      onComplete: () => {
        isAnalyzing.value = false
        message.success('分析完成')
      }
    })
  } catch (error: any) {
    message.error('分析出错：' + (error.message || '请稍后重试'))
    console.error('Name analysis error:', error)
    isAnalyzing.value = false
  } finally {
    analyzing.value = false
  }
}

// 保存结果
const saveResult = () => {
  if (!analysisResult.value) return

  const filename = `${formData.value.name}_姓名分析_${new Date().toLocaleDateString()}.md`
  const blob = new Blob([analysisResult.value], { type: 'text/markdown' })
  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = filename
  a.click()
  URL.revokeObjectURL(url)

  message.success('保存成功')
}

// 分享结果
const shareResult = () => {
  if (!analysisResult.value) return

  // 复制到剪贴板
  const textToCopy = `【AI姓名分析结果】\n姓名：${formData.value.name}\n\n${analysisResult.value}`
  
  navigator.clipboard.writeText(textToCopy).then(() => {
    message.success('已复制到剪贴板，可以分享给朋友了')
  }).catch(() => {
    message.error('复制失败，请手动复制')
  })
}

// 重置表单
const resetForm = () => {
  formData.value = {
    name: '',
    gender: '男',
    birthYear: null
  }
  analysisResult.value = ''
  isAnalyzing.value = false
  formRef.value?.restoreValidation()
}
</script>

<style scoped>
.name-analysis-container {
  padding: 20px;
}

/* 移动端样式优化 */
@media (max-width: 768px) {
  .name-analysis-container {
    padding: 12px;
  }
}

.empty-result {
  min-height: 400px;
  display: flex;
  align-items: center;
  justify-content: center;
}

@media (max-width: 768px) {
  .empty-result {
    min-height: 300px;
  }
}

.loading-state {
  min-height: 400px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  gap: 24px;
}

@media (max-width: 768px) {
  .loading-state {
    min-height: 300px;
  }
}

.analysis-result {
  animation: fadeIn 0.5s ease-in;
}

.streaming-result {
  min-height: 200px;
  max-height: 500px;
  overflow-y: auto;
  padding: 16px;
  background: #fafafa;
  border-radius: 8px;
  border: 1px solid #e4e4e7;

  .dark & {
    background: rgba(255, 255, 255, 0.03);
    border-color: rgba(255, 255, 255, 0.1);
  }
}

@media (max-width: 768px) {
  .streaming-result {
    min-height: 150px;
    max-height: 400px;
    padding: 12px;
  }
}

/* 优化Markdown内容显示 */
.streaming-result :deep(.markdown-body) {
  padding: 4px;
  background: transparent;
}

/* 流式渲染时的光标效果 */
.streaming-result.is-streaming::after {
  content: '▋';
  animation: blink 1s infinite;
  color: #ff69b4;
  font-weight: bold;
}

@keyframes blink {
  0%, 50% { opacity: 1; }
  51%, 100% { opacity: 0; }
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

:deep(.n-card) {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 20px rgba(0, 0, 0, 0.12);
  }
}

:deep(.n-form-item) {
  margin-bottom: 24px;
}

@media (max-width: 768px) {
  :deep(.n-form-item) {
    margin-bottom: 20px;
  }
}

:deep(.n-input) {
  font-size: 16px;
}

:deep(.n-radio-group) {
  font-size: 16px;
}

:deep(.n-button) {
  font-size: 16px;
  height: 44px;
}

@media (max-width: 768px) {
  :deep(.n-button) {
    height: 40px;
  }
}
</style>